package com.ok.runnable;

import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSON;
import com.ok.constant.WsMsgTypeEnum;
import com.ok.constant.WsUrlTypeEnum;
import com.ok.domain.WsMsg;
import com.ok.event.DcomWsSocket;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.ConcurrentHashMap;

/**
 * 与前端websocket 心跳
 */
@Slf4j
public class WsHeartbeatRunnable extends AbstractRunable {

    @Override
    public void run() {
        ConcurrentHashMap<String, DcomWsSocket> map = DcomWsSocket.webSocketServerMAP;
        while (this.run) {
            try {
                if (map.isEmpty()) {
                    continue;
                }
                map.forEach((k, v) -> {
                    try {
                        if (v.urlType.equals(WsUrlTypeEnum.H_A.getCode())){
                            WsMsg wsMsg = new WsMsg();
                            wsMsg.setWsMsgTime(DateUtil.now());
                            wsMsg.setWsMsgType(WsMsgTypeEnum.heartbeat.getCode());
                            wsMsg.setWsMsgBody("ping");
                            v.session.getBasicRemote().sendText(JSON.toJSONString(wsMsg));
                        }
                    } catch (Exception e) {
                        log.error("发送心跳消息失败", e);
                    }

                });

            } catch (Exception e) {
                log.error("发送前端心跳异常:", e);
            } finally {
                try {
                    Thread.sleep(1000 * 45);
                } catch (InterruptedException ignored) {

                }
            }
        }
    }
}
